package com.xdy.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xdy.reggie.common.R;
import com.xdy.reggie.dto.SetMealDto;
import com.xdy.reggie.entity.Category;
import com.xdy.reggie.entity.Dish;
import com.xdy.reggie.entity.SetMeal;
import com.xdy.reggie.entity.SetMealDish;
import com.xdy.reggie.service.CategoryService;
import com.xdy.reggie.service.SetMealDishService;
import com.xdy.reggie.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetMealController {

    @Resource
    private SetMealService setMealService;

    @Resource
    private CategoryService categoryService;

    @Resource
    private SetMealDishService setMealDishService;

    @PostMapping
//    @CacheEvict(value = "setmealCache",key = "#setMealDto.categoryId + '_' + #setMealDto.status")
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> save(@RequestBody SetMealDto setMealDto){
        log.info("添加套餐 ===> {}",setMealDto);
        setMealService.saveWithSetMealDish(setMealDto);
        return R.success("添加成功！");
    }

    @GetMapping("/page")
    public R<Page<SetMealDto>> page(int page,int pageSize,String name){
        Page<SetMeal> setMealPage = new Page<>(page,pageSize);
        Page<SetMealDto> pageInfo = new Page<>();
        LambdaQueryWrapper<SetMeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null,SetMeal::getName,name);
        queryWrapper.eq(SetMeal::getIsDeleted,0);
        setMealService.page(setMealPage, queryWrapper);
        BeanUtils.copyProperties(setMealPage,pageInfo,"records");
        List<SetMeal> records = setMealPage.getRecords();
        List<SetMealDto> setMealDtos = records.stream().map(item -> {
            SetMealDto setMealDto = new SetMealDto();
            BeanUtils.copyProperties(item,setMealDto);
            Category category = categoryService.getById(item.getCategoryId());
            setMealDto.setCategoryName(category.getName());
            return setMealDto;
        }).collect(Collectors.toList());
        pageInfo.setRecords(setMealDtos);
        return R.success(pageInfo);
    }

    @GetMapping("/{setMealId}")
    public R<SetMealDto> getById(@PathVariable Long setMealId){
        SetMeal setMeal = setMealService.getById(setMealId);
        LambdaQueryWrapper<SetMealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetMealDish::getSetmealId,setMealId);
        List<SetMealDish> list = setMealDishService.list(queryWrapper);
        SetMealDto setMealDto = new SetMealDto();
        BeanUtils.copyProperties(setMeal,setMealDto);
        setMealDto.setSetmealDishes(list);
        return R.success(setMealDto);
    }

    @PutMapping
//    @CacheEvict(value = "setmealCache",key = "#setMealDto.categoryId + '_' + #setMealDto.status")
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> update(@RequestBody SetMealDto setMealDto){
        log.info("修改套餐信息 ===> {}",setMealDto);
        setMealService.updateWithSetMealDish(setMealDto);
        return R.success("修改成功！");
    }

    /**
     * 停售或者起售
     * @return
     */
    @PostMapping("/status/{state}")
    /**
     * @CacheEvict清理缓存数据
     */
    @CacheEvict(value = "setmealCache",allEntries = true)//清除setmealCache下的所有缓存
    public R<String> stopOrStartSelling(@PathVariable Integer state,@RequestParam List<Long> ids){
        log.info("修改的状态 ===> {}",state);
        log.info("菜品ID ===> {}",ids);
        List<SetMeal> setMealList = ids.stream().map(item -> {
            SetMeal setMeal = new SetMeal();
            setMeal.setId(item);
            setMeal.setStatus(state);
            return setMeal;
        }).collect(Collectors.toList());
        setMealService.updateBatchById(setMealList);
        return R.success("成功！");
    }

    /**
     * 删除或批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteById(@RequestParam List<Long> ids){
        setMealService.removeWithSetMealDish(ids);
        return R.success("删除成功！");
    }

    @GetMapping("/list")
    /**
     * @CachePut注解直接把返回值加入到缓存
     * @Cacheable注解会先查询缓存，缓存命中直接返回，不再执行方法调用，未命中会调用方法，并且把返回值加入缓存
     */
    @Cacheable(value = "setmealCache",key = "#setMealDto.categoryId + '_' + #setMealDto.status",unless = "#result == null")
    public R<List<SetMeal>> list(SetMealDto setMealDto){
        log.info("套餐分类id ===> {}",setMealDto.getCategoryId());
        LambdaQueryWrapper<SetMeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetMeal::getCategoryId,setMealDto.getCategoryId());
        queryWrapper.eq(SetMeal::getStatus,1);
        queryWrapper.eq(SetMeal::getIsDeleted,0);
        queryWrapper.orderByDesc(SetMeal::getUpdateTime);
        List<SetMeal> setMealList = setMealService.list(queryWrapper);
        return R.success(setMealList);
    }
}
